package com.carryGo.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ClassName:WebUtils
 * package:guoban
 * Desription:
 *
 * @Date:2020/8/23 17:38
 * @Author: 邓攀
 */
public class WebUtils {

    //默认图片的保存路径(lt)
    public static String SAVE_PATH = "C:\\项目图片";
    static {
        File file = new File(SAVE_PATH);
        if (file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 拼接访问路径
     */
    public static String getPageName(String pageName) {
        return "/WEB-INF/views/" + pageName + ".jsp";
    }

    /**
     * 转发页面
     */
    public static void toRequestPage(HttpServletRequest request, HttpServletResponse response, String pageName) throws ServletException, IOException {
        request.getRequestDispatcher(getPageName(pageName)).forward(request,response);
    }

    /**
     * 将所有的参数转化为String,String的形式
     * @param paramsMap
     * @return
     */
    public static Map<String, String> parseMapParams(Map<String, String[]> paramsMap){
        Map<String, String> map = new HashMap<>();
        //遍历整个参数map集合
        for (String name : paramsMap.keySet()) {
            String[] values = paramsMap.get(name);
            String value = "";
            if (values.length == 1){
                //只有一个参数的
                value = values[0];
            } else if (values.length > 1){
                //如果一个name对应多个参数，用逗号拼接起来
                for (int i = 0; i < values.length; i++) {
                    value += values[i] + ",";
                    //System.out.println("name="+name+",value="+values[i]);
                }
                //去掉最后一个逗号
                value = value.substring(0, value.length()-1);
            }
            map.put(name, value);
        }
        return map;
    }

    /**
     * 将传递过来的字符串转换为与字段的类型相同
     * @param value 转换的字符串
     * @param type 转换的类型
     * @return 转换后的对象
     */
    public static Object reverseValue(String value, String type){
        Object obj = value;
        switch (type) {
            case "int":
                //转化成int类型
                try {
                    obj = (value==null)?0:Integer.parseInt(value);
                } catch (NumberFormatException e) {
                    obj = 0;
                }
                break;
            case "Integer":
                try {
                    obj = (value==null)?0:Integer.valueOf(value);
                } catch (NumberFormatException e) {
                    obj = 0;
                }
                break;
            case "long":
                try {
                    obj = (value==null)?0:Long.parseLong(value);
                } catch (NumberFormatException e) {
                    obj = 0;
                }

                break;
            case "Long":
                try {
                    obj = (value==null)?0:Long.valueOf(value);
                } catch (NumberFormatException e) {
                    obj = 0;
                }
                break;
            case "double":
                try {
                    obj = (value==null)?false:Double.parseDouble(value);
                } catch (NumberFormatException e) {
                    obj = false;
                }
                break;
            case "Double":
                try {
                    obj = (value==null)?false:Double.valueOf(value);
                } catch (NumberFormatException e) {
                    obj = false;
                }
                break;
        }
        return obj;
    }

    /**
     * 获取上传的文件
     *
     * @param partName 上传文件input中的name
     * @return path 文件的保存路径
     */
    public static String uploadFile(HttpServletRequest request, String partName) throws IOException, ServletException {
        Part part = request.getPart(partName);
        System.out.println("part"+part);
        //获取原始的文件名
        String srcName = part.getSubmittedFileName();
        System.out.println(srcName);
        if (srcName == null || srcName.equals("") || part.getSize() == 0) {
            return null;
        }
        //随机的一个编号
        String fileName = UUID.randomUUID().toString();
        //文件名后缀
        String suffix = srcName.substring(srcName.lastIndexOf("."));
        //保存路径
        String path = WebUtils.SAVE_PATH + "/" + fileName + suffix;
        //将\替换/
        path = path.replaceAll("\\\\", "/");
        part.write(path);
        return path;
    }

    /**
     * 将map集合转化成实体类
     */
    public static <T> T parseMap(Class<T> clas, Map<String, String> mapParams)  {
        //1.创建对象
        T t = null;
        try {
            t = clas.newInstance();
            //2.遍历这个集合
            Field[] fields = clas.getDeclaredFields();
            //直接遍历这个字段
            for (Field field : fields) {
                //取name
                String name = field.getName();
                //3.获取值
                String value = mapParams.get(name);
                //4.获取对应的字段
                //Field field = clas.getDeclaredField(name);
                //5.拼接set方法
                String setMethod = "set" + name.substring(0,1).toUpperCase()
                        + name.substring(1);
                //6.获取方法
                Method method = clas.getDeclaredMethod(setMethod, field.getType());
                //7.执行方法
                method.invoke(t, reverseValue(value, field.getType().getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //8.返回这个对象
        return t;
    }
    /**
     * 将前端的所有参数存储到实体类中
     */
    public static <T> T getBean(Class<T> clas, HttpServletRequest request) {
        return parseMap(clas,
                WebUtils.parseMapParams(request.getParameterMap()));
    }
    /**
     * 将信息通过ajax发送到前端
     */
    public static void sendMSG(HttpServletResponse response, String msg) {
        try {
            PrintWriter out = response.getWriter();
            out.write(msg);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一段随机的字符串
     */
    public static String getRandomString(){
        return UUID.randomUUID().toString().replaceAll("\\-", "").toUpperCase();
    }
}
